package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/joho/godotenv"
)

var (
	client *oss.Client
)

var (
	AccessKey       string
	AccessKeySecret string
	OssEndPoint     string
	BucketName      string
	uploadFileName  string
	help            bool
)

func uploadFile() {
	if AccessKey == "" || AccessKeySecret == "" || OssEndPoint == "" {
		fmt.Println("AccessKey or AccessKeySecret or OssEndPoint is Enpty")
		os.Exit(1)
	}
	if uploadFileName == "" {
		fmt.Println("请输入要上传的文件名")
		Usage()
		os.Exit(1)
	}

	bucket, err := client.Bucket(BucketName)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	err = bucket.PutObjectFromFile(uploadFileName, uploadFileName)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	time := 60 * 60
	downloadUrl, err := bucket.SignURL(uploadFileName, oss.HTTPGet, int64(time))
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(uploadFileName, "上传成功")
	// fmt.Println(uploadFileName, "文件的下载的地址为: ", downloadUrl, "下载链接", time, "后失效")
	fmt.Printf("%s的下载的地址为: %s, 下载链接%ds后失效", uploadFileName, downloadUrl, time)
}

func loadParams() {
	flag.BoolVar(&help, "h", false, "帮助信息")
	flag.StringVar(&uploadFileName, "f", "", "要上传的文件名")
	flag.Parse()
	if help {
		fmt.Println(OssEndPoint, `Usage：[-h] -f []是可选参数
-f: 上传文件 + 文件名,
-h: 帮助信息
`)
	}
}

func Usage() {
	fmt.Println(OssEndPoint, `Usage：[-h] -f []是可选参数
-f: 上传文件 + 文件名,
-h: 帮助信息
`)

}

func main() {
	loadParams()
	//  上传文件
	uploadFile()
}

func init() {
	err := godotenv.Load("unit_test.env")
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	AccessKey = os.Getenv("ALI_AK")
	AccessKeySecret = os.Getenv("ALI_SK")
	OssEndPoint = os.Getenv("ALI_OSS_ENDPOINT")
	BucketName = os.Getenv("ALI_BUCKET_NAME")
	c, err := oss.New(OssEndPoint, AccessKey, AccessKeySecret)
	if err != nil {
		panic(err)
	}
	client = c
}
